package net.mobgame.android;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import net.mobgame.android.control.MenuAdapter;
import net.mobgame.common.Constants;
import net.mobgame.common.Utils;
import net.mobgame.internet.NoInternetActivity;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.view.Window;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

//Ad network-specific imports (AdMob).
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.google.ads.AdRequest.ErrorCode;

public class HomeMessage extends SlidingFragmentActivity{
	private  WebView wikiview;
	private FrameLayout framelayout;
	private ButtonTopBar btntopbar;
	private ButtonBottomBar btnBottom;
	private SlidingMenu sliding_menu;
	private int leftLayout;
	private int centerLayout;
	private int rightLayout;

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Intent startNoInternet = new Intent(getApplicationContext(), NoInternetActivity.class); 
			startActivity(startNoInternet);

		}
	};
	String path;
	private AdView mAdView;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setTheme(com.actionbarsherlock.R.style.Theme_Sherlock_Light);
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		btntopbar = new ButtonTopBar();
		btnBottom = new ButtonBottomBar();
		initCommonView();
		setBarClick();
		setData();
		path = Utils.makeTempFolder();
		
		// Create the adView.
		mAdView = (AdView)findViewById(R.id.ad);
		mAdView.setAdListener(new MyAdListener());

	    AdRequest adRequest = new AdRequest();
		// Load the adView with the ad request.
	    mAdView.loadAd(adRequest);
		
	}

	private void initCommonView() {
		leftLayout = R.layout.activity_sliding_left;
		centerLayout = R.layout.activity_main;
		rightLayout = R.layout.activity_sliding_right;
		sliding_menu = getSlidingMenu();
		sliding_menu.setShadowWidthRes(R.dimen.shadow_width);
		sliding_menu.setShadowDrawable(R.drawable.shadow);
		sliding_menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sliding_menu.setFadeDegree(0.35f);
		sliding_menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		sliding_menu.setMenu(leftLayout);
		// Main view layout for the activity
		setContentView(centerLayout);
		// set the Behind View
		setBehindContentView(leftLayout);
		getSlidingMenu().setSecondaryMenu(rightLayout);
		getSlidingMenu().setMode(SlidingMenu.LEFT_RIGHT);
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		getSlidingMenu().setSecondaryShadowDrawable(R.drawable.shadowright);
		wikiview = (WebView)findViewById(R.id.web_view);
		framelayout = (FrameLayout)findViewById(R.id.framelayout);
		topBarView();
		bottomBarView();
		secondFragmentView();

	}

	private Button buttonSearch;
	ListView list_menu;
	public void secondFragmentView(){
		buttonSearch = (Button)findViewById(R.id.buttonSearch);
		list_menu = (ListView)findViewById(R.id.listview);
	}
	MenuAdapter adapter;
	public void setDataAdapter(){
		adapter = new MenuAdapter(this);
		list_menu.setAdapter(adapter);
		list_menu.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				onClickItemMenu(position);
			}
		});
	}

	public void onClickItemMenu(int position){
		String[] tempAdress = this.getResources().getStringArray(R.array.menuAdress);
		for (int i = 0; i < tempAdress.length; i++) {
			if (i == position) {
				String notify = getString(R.string.comming_site_selected);
				sliding_menu.showContent();
				setDataWebSite(tempAdress[i],notify);
				progressWait(notify);
			}
		}
	}

	public void setOnclickSearch(){					// execute on setBarClick
		final String notify = getString(R.string.notify_search);
		buttonSearch.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showNotify(notify);
			}
		});
	}

	public static final int progress_bar_type = 0;
	private ProgressDialog pDialog;
	protected void onProgressUpdate (String... progress){
		pDialog.setProgress(Integer.parseInt(progress[0]));
	}
	String fileName;
	public class DownloadFromMobgame extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... arrayUrl) {
			int count;
			OutputStream output = null;
			try {
				path = Utils.makeTempFolder();
				URL url = new URL(arrayUrl[0]);
				URLConnection connection = url.openConnection();
				connection.connect();
				int lengthOfFile = connection.getContentLength();
				InputStream input = new BufferedInputStream(url.openStream());
				if (Utils.hasStorage()) {
					fileName = Utils.getFileName(url_download, "/");
					output = new FileOutputStream(path + "/" + fileName);
//					Log.d("Folder games: ",path + fileName);
				}
				byte[] data = new byte[1024];
				long total = 0;
				while ((count = input.read(data)) != -1) {
					total += count;
					publishProgress(""+(int)((total*100)/lengthOfFile));
					output.write(data, 0, count);
				}
				output.flush();
				output.close();
				input.close();
			} catch (Exception e) {e.printStackTrace();}
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			try {
				if (dialog.isShowing()) {
					dialog.cancel();
				}
			} catch (Exception e) {e.printStackTrace();}
			showCustomDialog(getString(R.string.dialog_install_title), 
					getString(R.string.dialog_install_content), 
					getString(R.string.dialog_install_button),false);
		}
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showCustomDialog(getString(R.string.dialog_download_title), 
					getString(R.string.dialog_download_content), 
					getString(R.string.dialog_donwload_button),true);
		}
	}
	Dialog dialog;
	public void showCustomDialog(String title, String content, final String textButton, final boolean downloadOrInstall){
		dialog = new Dialog(this);
		dialog.setContentView(R.layout.custom_dialog);
		dialog.setTitle(title);
		// set the custom dialog components - text, image and button
//		TextView textTitle = (TextView)dialog.findViewById(R.id.textTitle);
		TextView text = (TextView) dialog.findViewById(R.id.txt_message);
		text.setText(content);
		RelativeLayout progressbarDownload = (RelativeLayout)dialog.findViewById(R.id.progressbarDownload);
		ImageView image = (ImageView) dialog.findViewById(R.id.image_dialog);
		image.setImageResource(R.drawable.ic_launcher);
		Button dialogButtonOk = (Button) dialog.findViewById(R.id.dialogButtonOK);
		Button dialogButtonCancle = (Button) dialog.findViewById(R.id.dialogButtonCancle);
		if (downloadOrInstall) {
			progressbarDownload.setVisibility(View.VISIBLE);
			image.setVisibility(View.INVISIBLE);
			dialogButtonCancle.setVisibility(View.GONE);
		}else{
			progressbarDownload.setVisibility(View.INVISIBLE);
			image.setVisibility(View.VISIBLE);
			dialogButtonCancle.setVisibility(View.VISIBLE);
		}
		dialogButtonOk.setText(textButton);
		// if button is clicked, close the custom dialog
		dialogButtonOk.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String stringEqual = getString(R.string.dialog_install_button);
				if (textButton.equals(stringEqual)) {
					File exePathFile = new File(Environment.getExternalStorageDirectory() + Constants.MOBGAME_PATH_GAME + "/" + fileName);
					executeFileDownload(exePathFile);
				}
				dialog.hide();
			}
		});
		dialogButtonCancle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.hide();
			}
		});
		dialog.show();
	}

	public static class CustomDialog extends Dialog{
		private static CustomDialog singleObject;
		private CustomDialog(Context context) {
			super(context);
		}

		public static CustomDialog getInstance(Context context){
			if (singleObject == null) {
				singleObject = new CustomDialog(context);
			}
			return singleObject;
		}
	}

	public void executeFileDownload(File pathFile){
		Intent installIntent = new Intent(Intent.ACTION_VIEW);
		File fileExe = pathFile;
		installIntent.setDataAndType(Uri.fromFile(fileExe), "application/vnd.android.package-archive");
//		Log.d("EXE File: ", "" + String.valueOf(fileExe));
		startActivity(installIntent);
	}

	public void showNotify(String notify){
		Toast.makeText(this, notify, Toast.LENGTH_LONG).show();
	}

	public void topBarView(){
		btntopbar.buttonLeft = (Button)findViewById(R.id.buttonLeft);
		btntopbar.buttonRight = (Button)findViewById(R.id.buttonRight);
	}
	public void bottomBarView(){
		btnBottom.buttonBack = (Button)findViewById(R.id.buttonBack);
		btnBottom.buttonHome = (Button)findViewById(R.id.buttonHome);
	}

	public void setData(){
		setDataAdapter();
		setDataWebSite("http://www.mobgame.net",getString(R.string.progress));
	}
	String url_download;
	@SuppressLint("SetJavaScriptEnabled")
	public void setDataWebSite(String address, final String progress){
		WebSettings webSettings = wikiview.getSettings();
		webSettings.setJavaScriptEnabled(true);
		wikiview.loadUrl(address);
		wikiview.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				progressWait(progress);
				Log.d("shouldOverrideUrlLoading", url);
				view.loadUrl(url);
				return true;
			}
		});
		wikiview.setDownloadListener(new DownloadListener() {
			public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
				url_download = url;
				new DownloadFromMobgame().execute(url);
			}
		});
	}

	public void setBarClick(){
		btntopbar.buttonLeft.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				sliding_menu.showMenu(true);
			}
		});
		btntopbar.buttonRight.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				sliding_menu.showSecondaryMenu();
			}
		});
		btnBottom.buttonBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				backWebSite();
				progressWait(getString(R.string.progress_back));
			}
		});
		btnBottom.buttonHome.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setData();
			}
		});
		setOnclickSearch();
	}

	public void backWebSite(){
		if (wikiview.canGoBack()) {
			wikiview.goBack();
		}
	}

	public void progressWait(final String string){
		final TextView txtViewProcess = (TextView)findViewById(R.id.txtViewProcess);
		CountDownTimer timer = new CountDownTimer(4000, 1000) {
			@Override
			public void onTick(long millisUntilFinished) {
				txtViewProcess.setText(string);
				framelayout.setVisibility(View.VISIBLE);
			}
			@Override
			public void onFinish() {
				framelayout.setVisibility(View.GONE);
			}
		};
		timer.start();
	}

	@Override
	public void onResume() {
		super.onResume();
		// Register no internet broadcast to launch no internet connectivity
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constants.NO_INTERNET_ACTION);
		registerReceiver(receiver, filter);
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiver);
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onBackPressed() {
		final AlertDialog dlgExit = new AlertDialog.Builder(this).create();
		dlgExit.setMessage(getString(R.string.alert_quit_app));
		dlgExit.setButton(getString(R.string.button_yes), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				moveTaskToBack(true);
			}
		});
		dlgExit.setButton2(getString(R.string.button_no), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dlgExit.dismiss();
			}
		});
		dlgExit.show();
	}

	public class ButtonTopBar {
		private Button buttonLeft;
		private Button buttonRight;
		public ButtonTopBar() {
			super();
		}
	}

	public class ButtonBottomBar{
		Button buttonHome,buttonBack;
	}

	private TextView mAdStatus;
	// Receives callbacks on various events related to fetching ads.  In this sample,
    // the application displays a message on the screen.  A real application may,
    // for example, fill the ad with a banner promoting a feature.
    private class MyAdListener implements AdListener {

        @Override
        public void onDismissScreen(Ad ad) {}

        @Override
        public void onFailedToReceiveAd(Ad ad, ErrorCode errorCode) {
            mAdStatus.setText(R.string.error_receive_ad);
        }

        @Override
        public void onLeaveApplication(Ad ad) {}

        @Override
        public void onPresentScreen(Ad ad) {}

        @Override
        public void onReceiveAd(Ad ad) { mAdStatus.setText(""); }
    }
}
